package com.theatre.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.theatre.userservice.mapper.PublisherMapper;
import com.theatre.userservice.mapper.ScriptMapper;
import com.theatre.userservice.mapper.ShopMapper;
import com.theatre.userservice.model.entity.Publisher;
import com.theatre.userservice.model.entity.Script;
import com.theatre.userservice.model.entity.Shop;
import com.theatre.userservice.model.vo.PublisherVO;
import com.theatre.userservice.model.vo.ScriptVO;
import com.theatre.userservice.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {
    @Autowired
    private ScriptMapper scriptMapper;

    @Autowired
    private PublisherMapper publisherMapper;

    @Override
    public List<ScriptVO> selectPurchased(Long shopId) {
        // 1. 查询该商铺已购买的剧本列表
        List<Script> scripts = scriptMapper.selectList(
                new QueryWrapper<Script>().eq("shop_id", shopId)
        );

        if (scripts == null || scripts.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 构建结果列表
        List<ScriptVO> result = new ArrayList<>();

        for (Script script : scripts) {
            ScriptVO vo = new ScriptVO();
            vo.setId(script.getId());
            vo.setTitle(script.getTitle());
            vo.setAuthor(script.getAuthor());
            vo.setDescription(script.getDescription());
            vo.setContentFile(script.getContentFile());
            vo.setPublisherId(script.getPublisherId());
            vo.setCategoryId(script.getCategoryId());
            vo.setPrice(script.getPrice());
            vo.setStatus(script.getStatus());
            vo.setSold(script.getSold());
            vo.setUsageDays(script.getUsageDays());
            vo.setExpireTime(script.getExpireTime());

            // 3. 查询发行商信息
            Publisher publisher = publisherMapper.selectById(script.getPublisherId());
            if (publisher != null) {
                PublisherVO publisherVO = new PublisherVO();
                publisherVO.setId(publisher.getId());
                publisherVO.setUserId(publisher.getUserId());
                publisherVO.setName(publisher.getName());
                publisherVO.setPhone(publisher.getPhone());
                publisherVO.setEmail(publisher.getEmail());
                vo.setPublisherVO(publisherVO);
            }

            result.add(vo);
        }

        return result;
    }
}
